<?php

    global $mikron;
    
    $mikron->Page->StartBody();

    /**
    * Preparing page data
    */
    $pageindex = 2;
    $prevpage = "page1.php";
    $nextpage = "page3.php";
    $nextbutton_action = "checkcode();";
    define("MAX_SPEC_COUNT", 5);
    $_SESSION['recordresult'] = null;
    $form_values = Array();
    $checked_specs = Array();
    if(isset($_SESSION['form']))
    {
        // При возврате со следующей страницы обратно сюда
        $form_values = $_SESSION['form'];
        $checked_specs = $form_values['dict']['spec'];
    }

    // Определение выбранного пациента
    $personId = isset($_GET['person']) ? $_GET['person'] : $mikron->Cache->getCache('personid');
    if(!is_numeric($personId))
    {
        $mikron->Tools->GoToPage('Location: /remoterecord/?needperson');
    }
    $personId = (int)$personId;
    $person = new T_PERSON($personId);
    if($person->cabinet->value->id != $mikron->Users->CurrentUser()->id())
    {
        $mikron->Tools->GoToPage('Location: /remoterecord/?invalidperson');
    }
    $mikron->Cache->setCache('personid', $personId);

    // Определение выбранного ЛПУ
    $lpu_guid = isset($_GET['lpu']) ? $_GET['lpu'] : $mikron->Cache->getCache('lpuguid');
    if(is_null($lpu_guid))
    {
        $mikron->Tools->GoToPage('Location: /remoterecord/?needlpu');
    }
    $mikron->Cache->setCache('lpuguid', $lpu_guid);

    /**
    * Получение расписания из кеша или с сервера
    */
    function getSchedule()
    {
        global $mikron;
        $buf = $mikron->Cache->getCache('resource_schedule');
        if(is_null($buf))
        {
            $mikron->EntityManager->DeleteEntity('RS_LPU', '*', true);
            $mikron->EntityManager->DeleteEntity('RS_SCHEDULE', '*', true);
            $mikron->EntityManager->DeleteEntity('RS_SPECIALITY', '*', true);
            $mikron->EntityManager->DeleteEntity('RS_RESOURCE', '*', true);
            $mikron->EntityManager->DeleteEntity('RS_DAYITEM', '*', true);
            $getRemoteScheduleXML = CreateGetResourceScheduleXML(Array(), constant('DATEBEGIN'), constant('DATEEND'));
            $buf = CallSoap('resourceschedule', $getRemoteScheduleXML);
            $mikron->Cache->setCache('resource_schedule', $buf);
            $dom1 = new DomDocument();
            $dom1->loadXML($buf);
            $rsLPU = new RS_LPU();
            $rsLPU->name->value = 'Детская пол-ка №0.';
            $mikron->EntityManager->Save(Array($rsLPU), false);
            $resourceschedules = $dom1->getElementsByTagName('resourceschedule');
            $i = 0;
            $days = Array();
            foreach($resourceschedules as $resourceschedule)
            {
                $rs = new RS_SCHEDULE();
                $rs->lpu->value = $rsLPU->id;
                $mikron->EntityManager->Save(Array($rs), false);
                $specialities = $resourceschedule->getElementsByTagName('speciality');
                foreach($specialities as $speciality)
                {
                    // Создание специальности
                    $spec = new RS_SPECIALITY();
                    $spec->code->value = $speciality->getAttribute("code");
                    $spec->name->value = $speciality->getAttribute("name");
                    $mikron->EntityManager->Save(Array($spec), false);
                    $resources = $speciality->getElementsByTagName("resource");
                    foreach($resources as $resource)
                    {
                        $rc = new RS_RESOURCE();
                        $rc->code->value = $resource->getAttribute("code");
                        $rc->fio->value = $resource->getAttribute("fio");
                        $rc->moment->value = $resource->getAttribute("moment");
                        $rc->place->value = $resource->getAttribute("place");
                        $rc->speciality->value = $spec->id;
                        $rc->schedule->value = $rs->id;
                        $mikron->EntityManager->Save(Array($rc), false);
                        $dayitems = $resource->getElementsByTagName('dayitem');
                        foreach($dayitems as $dayitem)
                        {
                            $di = new RS_DAYITEM();
                                $di->dayofweek->value = $dayitem->getAttribute("daysofweek");
                                $di->workbegin->value = $dayitem->getAttribute("workbegin");
                                $di->workend->value = $dayitem->getAttribute("workend");
                                $di->resource->value = $rc->id;
                            $days[] = $di;
                        }
                    }
                }
            }
            $mikron->EntityManager->Save($days, false);
            $mikron->EntityManager->CloseTransaction();
        }
    }
    
    getSchedule();

    /**
    * Default values
    */
    $form_values['uniqueid'] = $person->uniqueid->value;
    $form_values['birthday'] = date("d.m.Y", strtotime($person->birthday->value));
    $form_values['lastname'] = $person->lastname->value;
    $form_values['firstname'] = $person->firstname->value;
    $form_values['middlename'] = $person->fathername->value;
    $form_values['sex'] = $person->sex->value;
    $form_values['insurance_company'] = null;
    $form_values['policy_serial'] = $person->omsseries->value;
    $form_values['policy_number'] = $person->omsnumber->value;
    $form_values['target_date'] = date("d.m.Y");
    $form_values['director'] = 2;
    $form_values['direction_perpose'] = 2;

    require_once(dirname(__FILE__).'/info.inc');

?>
<h1>Выберите специалистов, к которым Вы хотите произвести запись:</h1>
<?php

    function DrawSchedule()
    {
        global $mikron, $checked_specs;
        mt_srand();
        $groupitem = 0;
        $spec_index = 0;
        ?>
        <div class="schedule">
            <?php

            $resource = new RS_RESOURCE();
            $di = new RS_DAYITEM();
            $rs = $mikron->Queries->Query('RS_SCHEDULE');
            if($rs->count() == 0)
            {
                ?>Расписание отсутствует.<?php
                $frm = new html_form('schedule_error', 'get', '/remoterecord/');
                $frm->addSubmit('gobutton', 'Назад');
                $frm->end();
                return;
            }

            $rs = $rs->fetch();
            $specs = Array();
            $tbl1 = new html_table(9, 'rschedule_speciality', '', 0, 0);
            while($resource = $rs->resources->value->fetch())
            {
                $checked = in_array($resource->speciality->value->code->value, $checked_specs);
                if($checked){$checkedattr=" checked ";}else{$checkedattr = null;}
                $speciality_code = $resource->speciality->value->code->value;
                $speciality_name = $resource->speciality->value->name->value;
                if(!in_array($speciality_code, $specs))
                {
                    if(count($specs) > 0)
                    {
                        $rowid = $groupid.'_'.$groupitem++;
                        $tbl1->newrow($rowid);
                            $tbl1->newcol('&nbsp;', false, false, $rowid, null, '', null, null, 9, true);
                    }
                    $groupid = 'g_'.md5(time().mt_rand(0, 9999999));
                    $groupitem = 0;
                    // new row
                    $tbl1->newcol(null, true, true, null, 'rschedule_speciality_checkbox', '', 'middle',null,null,false);
                        ?><input <?php echo $checkedattr; ?> type="checkbox" name="form_values[dict][spec][]" value="<?php echo $speciality_code;?>" onclick="javascript: opengroup('<?php echo $groupid; ?>', this.checked);"><?php
                    $tbl1->newcol($speciality_name, false, false, null, 'rschedule_speciality_name', '', null, null, 8);
                    $specs[] = $speciality_code;
                    $rowid = $groupid.'_'.$groupitem++;
                    // new row
                    $tbl1->newcol(null, false, false, $rowid, null, '', null, null, null, !$checked);
                    $tbl1->newcol(null, false, false, null, 'daycell', '');
                    $tbl1->newcol('Пн', false, false, null, 'daycell', '');
                    $tbl1->newcol('Вт', false, false, null, 'daycell', '');
                    $tbl1->newcol('Ср', false, false, null, 'daycell', '');
                    $tbl1->newcol('Чт', false, false, null, 'daycell', '');
                    $tbl1->newcol('Пт', false, false, null, 'daycell', '');
                    $tbl1->newcol('Сб', false, false, null, 'daycell', '');
                    $tbl1->newcol('Вс', false, false, $rowid, 'daycell', '');
            }
                $rowid = $groupid.'_'.$groupitem++;
                // new row
                $tbl1->newcol(null,false,false,$rowid,null,'',null, null, null, !$checked);
                $tbl1->newcol($resource->fio->value, true,false, null, 'schedule_fio','');
                while($di = $resource->dayitems->value->fetch())
                {
                    if($di->workbegin->value == '')
                    {
                        $di_value = '&nbsp;';
                    }
                    else
                    {
                        $begin = $di->workbegin->value;
                        $end = $di->workend->value;
                        $begin = (int)str_replace(':00', null, $begin);
                        $end = (int)str_replace(':00', null, $end);
                        $di_value = $begin.'–'.$end;
                    }
                    $tbl1->newcol("<span>$di_value</span>", false, false, null, 'period');
                }
            }
            $tbl1->end();
            ?>
        </div>
        <script type="text/javascript">
            function opengroup(groupname, value)
            {
                for(var i = 0; i < 999; i++)
                {
                    var id = groupname+'_'+i;
                    var o = document.getElementById(id);
                    if(o == null)
                    {
                        return;
                    }
                    if(o.length < 1)
                    {
                        return;
                    }
                    o.style.display = value?'':'none';
                }
            }
        </script>
        <?php
    }

    require_once(dirname(__FILE__).'/dictionaries.inc');
    $dictionaries = new dictionaries_class($lpu_guid);

?>

<table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
    <td style="height: 5%; vertical-align: bottom; text-align: left; padding-bottom: 0em; ">
        <form action="<?php echo $nextpage;?>" method="post" onsubmit="return validate(this, validatelist);">
            <table border="0" cellspacing="0" cellpadding="1">
                <div style="position: absolute; width: 0px; height: 0px; left: -900px; ">
                    Дата направления: <input type="hidden" name="form_values[target_date]">
                    <br /><select name="form_values[director]" onchange="change_target_director('form_values[employment]', this.options.value);"></select>
                    <div id='dvEmployment' style="display: none; ">
                        <br />Занятость: <select name="form_values[employment]"></select>
                    </div>
                    <br />Цель направления: <select name="form_values[direction_perpose]"></select>
                    <br />Пациент: <input name="form_values[uniqueid]">
                </div>
                <tr><td colspan="2"><?php DrawSchedule(); ?></td></tr>
                <tr>
                    <td colspan="2">
                        <input type="submit" onclick="location.href='/remoterecord/lpulist.php?person=<?php echo $person->id; ?>'; return false;" value="Назад">
                        <input type="submit" value="Далее">
                        <input type="submit" onclick="location.href='/remoterecord/'; return false;" value="Отмена">
                    </td>
                </tr>
                </table>
        </form>
        
        <script type="text/javascript">
            // составление справочников
            var DirectionPerpose = <?php echo createDictForJS($dictionaries->dic, 'DirectionPerpose'); ?>;
            var DocType = <?php echo createDictForJS($dictionaries->dic, 'DocType'); ?>;
            var InsuranceCompany = <?php echo createDictForJS($dictionaries->dic, 'InsuranceCompany'); ?>;
            var Speciality = <?php echo createDictForJS($dictionaries->dic, 'speciality'); ?>;
            var Sex = <?php echo createDictForJS($dictionaries->dic, 'Sex'); ?>;
            var Director = <?php echo createDictForJS($dictionaries->dic, 'director'); ?>;
            var Employment = <?php echo createDictForJS($dictionaries->dic, 'employment'); ?>;
            var PolicySerialMask = "";
            var PolicyNumberMask = "";

            // заполнение списков данными из справочников
            fill("form_values[direction_perpose]", DirectionPerpose);
            fill("form_values[director]", Director);
            fill("form_values[employment]", Employment);

            <?php

            /*for($i=0;$i<constant("MAX_SPEC_COUNT");$i++)
            {
                ?>
                fill("form_values[dict][spec][<?php echo $i;?>]", Speciality);
                <?php
            }*/
            ?>

            // правила валидации формы
            var validatelist = [
                ['form_values[director]', 'selectisnotnull', 'alert("Выберите кем направляется.");'],
                ['form_values[direction_perpose]', 'selectisnotnull', 'alert("Выберите цель направления.");'],
                ['form_values[dict][spec][]', 'oneormorechecked', 'alert("Выберите специальность.");'],
                ['form_values[employment]', 'required', 'alert("Укажите занятость.");', 'dvEmployment']
            ];

            <?php 

                if(count($form_values) > 0)
                {
                    ?>
                    // Восстановление введенных данных при возврате со следующей страницы
                    setValue('form_values[uniqueid]',   '<?php echo getArrayValue($form_values, 'uniqueid');?>');
                    setValue('form_values[direction_perpose]',   '<?php echo getArrayValue($form_values, 'direction_perpose');?>');
                    setValue('form_values[director]',   '<?php echo getArrayValue($form_values, 'director');?>');
                    setValue('form_values[employment]',   '<?php echo getArrayValue($form_values, 'employment');?>');
                    setValue('form_values[target_date]',        '<?php echo getArrayValue($form_values, 'target_date');?>');
                    setValue('form_values[direction_perpose]',        '<?php echo getArrayValue($form_values, 'direction_perpose');?>');
                    <?php
                }
            else
            {
                ?>
                setValue('form_values[direction_perpose]', 2);
                if(Director.length == 2)
                {
                    setValue('form_values[director]', Director[1][0]);
                }
                <?php
            }
            if(count($form_values) > 0)
            { ?>
                change_target_director('form_values[employment]', '<?php echo getArrayValue($form_values, 'director');?>');
                 <?php
            }?>

            // функция заполнения списков данными из справочников
            function fill(selectBoxName, dict)
            {
                var elm = document.getElementsByName(selectBoxName);
                if(elm != null)
                {
                    oList = elm[0];
                    for (var i = 0; i < dict.length; i++)
                    {
                        var code = dict[i][0];
                        var value = dict[i][1];
                        if (document.createElement)
                        {
                            var opt = document.createElement("OPTION");
                            opt.text = value;
                            opt.value = code;
                            // тут мы используем для добавления элемента либо метод IE,
                            // либо DOM, которые, alas, не совпадают по параметрам…
                            (oList.options.add) ? oList.options.add(opt) : oList.add(opt, null);
                        }
                        else
                        {
                            // для NN3.x-4.x
                            oList.options[i] = new Option(value, code, false, false);
                        }
                    }
                }
            }
            
            function change_target_director(changed_field, value)
            {
                var elm = document.getElementsByName(changed_field);
                var EmploymentDiv = document.getElementsByName('dvEmployment');
                if((elm != null) && (EmploymentDiv != null))
                {
                    elm = elm[0];
                    EmploymentDiv = EmploymentDiv[0];
                    switch(value)
                    {
                        case '9': case '10':
                            EmploymentDiv.style.display = '';
                            break;
                        default:
                            EmploymentDiv.style.display = 'none';
                            break;
                    }
                }
            }

            // изменение серии полиса при изменении страховой компании
            function change_insurance_company(changed_field, selected_key)
            {
                var elm = document.getElementsByName(changed_field);
                if(elm != null)
                {
                    elm = elm[0];
                    // changed_field — имя изменяемого поля
                    // selected_key — выбранный код элемента
                    var template = selected_key.split(",");
                    var code = '';
                    if(template.length == 2)
                    {
                        code = template[0];
                        template = template[1];
                    }
                    else
                    {
                        code = '';
                        template = '';
                    }

                    elm.disabled = (template != "");
                    var objInsuranceExtInfo = document.getElementById('InsuranceExtInfo');
                    elm.style.backgroundColor = elm.disabled?'#f0f0e0':'';
                    objInsuranceExtInfo.style.display = elm.disabled?'none':'';

                    PolicySerialMask = "";
                    PolicyNumberMask = "";
                    if(template != "")
                    {
                        var series = template.split("|");
                        if(series.length > 0)
                        {
                            elm.value = series[0];
                            PolicySerialMask = series[0];
                            if(series.length > 1)
                            {
                                PolicyNumberMask = series[1];
                            }
                        }
                    }
                    else
                    {
                        // нулевое значение
                        elm.value = '';
                    }
                }
            }

            // событие при изменении типа документа
            function changeDocType(value, elements)
            {
                for (var i = 0; i < elements.length; i++)
                {
                    var ele = document.getElementsByName(elements[i]);
                    if(ele != null)
                    {
                        ele = ele[0];
                        ele.disabled = (value == null || value == 99);
                        ele.style.backgroundColor = ele.disabled?'#f0f0e0':'';
                    }
                }
            }

        </script>

    </td>
</tr>
</table>

<script type="text/javascript" src="/functions.js"></script>

<?php 

    // функция экспорта PHP массива в JavaScript массив
    function createDictForJS($dictionary, $key)
    {
        if(!array_key_exists($key, $dictionary))
        {
            return "null";
        }
        $dic = $dictionary[$key];
        $i = 0;
        $a = Array();
        // $a[] = "['','']";
        foreach($dic as $code => $value)
        {
            $a[] = "['$code','$value']";
        }
        echo "[".implode(",", $a)."]";
    }

    function getArrayValue($arr, $key)
    {
        $ret = "";
        $keys = $key;
        if(!is_array($keys))
        {
            $v = $keys;
            $keys = Array();
            $keys[] = $v;
        }
        foreach($keys as $k)
        {
            if(!array_key_exists($k, $arr))
            {
                break;
            }
            $arr = $arr[$k];
            $ret = $arr;
        }
        return $ret;
    }

$mikron->Page->EndBody(); ?>